package com.daffodil.storage.exception.handler;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.server.ResponseStatusException;

import com.daffodil.storage.exception.BaseException;
import com.daffodil.storage.model.JsonResult;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author yweijian
 * @date 2023年10月30日
 * @version 1.0
 * @description
 */
@Slf4j
@RestControllerAdvice
public class StorageExceptionHandler {
    
    /**
     * -拦截响应异常
     */
    @ExceptionHandler(ResponseStatusException.class)
    public JsonResult handleResponseStatusException(ResponseStatusException e) {
        log.error("请求响应异常[{}]", e.getMessage(), e);
        return JsonResult.error(e.getRawStatusCode(), HttpStatus.valueOf(e.getRawStatusCode()).name());
    }
    
    /**
     * -拦截校验验证异常
     */
    @ExceptionHandler(WebExchangeBindException.class)
    public JsonResult handleValidatedBindException(WebExchangeBindException e) {
        log.error("校验参数异常[{}]", e.getMessage(), e);
        String errcode = e.getAllErrors().get(0).getCode();
        String message = e.getAllErrors().get(0).getDefaultMessage();
        int code = HttpStatus.BAD_REQUEST.value();
        try {
            code = Integer.valueOf(errcode);
        }catch (Exception ignore) {
            
        }
        return JsonResult.error(code, message);
    }
    
    /**
     * -拦截应用基础异常
     */
    @ExceptionHandler(BaseException.class)
    public JsonResult handleBaseException(BaseException e) {
        log.error("应用基础异常[{}]", e.getMessage(), e);
        return JsonResult.error(e.getCode(), e.getMessage());
    }
    
    /**
     * -拦截运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public JsonResult handleRuntimeException(RuntimeException e) {
        log.error("运行时异常[{}]", e.getMessage(), e);
        return JsonResult.error("系统运行错误，请联系管理员");
    }

    /**
     * -拦截系统异常
     */
    @ExceptionHandler(Exception.class)
    public JsonResult handleException(Exception e) {
        log.error("服务器异常[{}]", e.getMessage(), e);
        return JsonResult.error("服务器内部错误，请联系管理员");
    }

}
